package com.implemetsystem.prestacontas.geral.exception;

import java.util.Iterator;

import javax.enterprise.context.NonexistentConversationException;
import javax.faces.FacesException;
import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.FacesContext;
import javax.faces.event.ExceptionQueuedEvent;
import javax.faces.event.ExceptionQueuedEventContext;

import com.implemetsystem.prestacontas.geral.utils.FacesUtil;

public class ErpExceptionHandler extends ExceptionHandlerWrapper {
	
	  private ExceptionHandler wrapped;

	  public ErpExceptionHandler(ExceptionHandler wrapped) {
	    this.wrapped = wrapped;
	  }

	  @Override
	  public ExceptionHandler getWrapped() {
	    return wrapped;
	  }

	  @Override
	  public void handle() throws FacesException {
	    //iterar nas exceptions não tratadas
	    Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();
	    while (i.hasNext()) {
	      ExceptionQueuedEvent event = i.next();
	      ExceptionQueuedEventContext context =
	        (ExceptionQueuedEventContext)event.getSource();

	      Throwable t = context.getException();

	      //Tratar exception, redirecionar, ignorar, etc...
	      try{
	    	System.out.println("********************************************************");
	        System.out.println("DEBUG EXCEPTION CAPTURADA: " + t.getMessage());
	        System.out.println("********************************************************");
	        t.printStackTrace();
	        String destino = "/erro.xhtml";      
	        
	        if(t instanceof NonexistentConversationException){        	
	        	destino = "/login.xhtml";
	        	FacesUtil.mensInfo("Tempo de sessão expirada. faça login novamente.");
	        }
	        
			// Redireciona para a pagina que a variável destino está indicando
	        FacesContext.getCurrentInstance().getApplication().getNavigationHandler().handleNavigation(
    			  FacesContext.getCurrentInstance(), null, destino);	      

	      } finally{
	        //tratada, remove-la
	        i.remove();
	      }
	    }
	    getWrapped().handle();
	  }
}
